import { ref, reactive } from 'vue'
import { getToken } from '@/stores/useApp.js'
import { domain } from '@/stores/useApp.js'

const defaultAvatar = "https://www.lin-home.com/default.png";
const user = reactive({
	nickName: "",
	avatar: defaultAvatar,
	mobile: ""
});

//更改昵称
async function modifyNickName (nickName) {
	if (nickName.length === 0 || nickName.length > 12) {
		// 必须输入昵称，并且昵称要小于12个字符。
		uni.showModal({
		    title: '提示',
		    content: '没有输入昵称，请重新填写',
			showCancel: false,
			confirmColor: '#707092',
		    success: function (res) {
				console.log("ok!")
			},
		    fail:function (res) {
				console.log("error!")
			}
		})
	}
	else{
		uni.showLoading({
			title: '加载中'
		});
		
		user.nickName = nickName;
		let msg = await uni.post("/api/uc/ModifyRealName", {
			realName: nickName
		});
		if(msg.success) {
			await getUserInfo();
			uni.hideLoading();
			uni.redirectTo({
				url: './Personal'
			});
		}
	}
}

//更改头像
async function modifyAvatar (avatar) {
	if(avatar.length > 409600){
		uni.showModal({
		    title: '提示',
		    content: '图片大小超过限制400kb，请重新选择',
			showCancel: false,
			confirmColor: '#707092',
		})
	}
	else{
		uni.showLoading({
			title: '加载中'
		});
		
		await uni.post("/api/uc/ModifyAvatar", {
			avatar: avatar
		});
		await getUserInfo();
		uni.hideLoading();
		user.avatar = avatar;	
	}
}

//更改手机号
async function modifyMobile (mobile) {
	if (mobile.length !== 11) {
		// 手机号长度只能为11
		uni.showModal({
		    title: '提示',
		    content: '手机号输入长度不正确，请重新填写',
			showCancel: false,
			confirmColor: '#707092',
		})
	}
	else{
		uni.showLoading({
			title: '加载中'
		});
		let msg = await uni.post("/api/uc/ModifyMobile", {
			mobile: mobile
		});
		if(msg.success) {
			await getUserInfo();
			uni.hideLoading();
			uni.redirectTo({
				url: './Personal'
			});
		}
		
	}
}

async function getUserInfo () {
	let token = await getToken();
	
	let msg = await uni.post("/api/uc/GetProfile"); // { success: true, msg: "", data: { RealName: "张三", Mobile: "13355558888", Avatar: "" } } // 
	user.nickName = msg.RealName;
	user.avatar = msg.Avatar ? `${domain}${msg.Avatar}` : defaultAvatar;
	user.mobile = msg.Mobile;
	console.log(user);
}

function useCurrentUser() {
	return {
		user,
		modifyNickName,
		modifyAvatar,
		modifyMobile,
		getUserInfo
	}
}

export {
	useCurrentUser,
}